<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="600px"
    :destroyOnClose="true"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #before="{ model, field }">
        <FormItemRest>
          <div class="flex items-center">
            <!-- <Switch v-model:checked="model[field]" checkedChildren="是" unCheckedChildren="否" /> -->
            <Select
              style="width: 100px; margin: 0 10px"
              v-model:value="model[field]"
              defaultValue="1"
              :options="timeRemind"
            />
            之前
          </div>
        </FormItemRest>
      </template>
      <template #give>
        <FormItemRest>
          <Space>
            <Checkbox v-model:checked="dataRef.mine">自己</Checkbox>
            <Checkbox
              v-model:checked="dataRef.others"
              :disabled="isUpdate && dataRef.others && !isMultiDeptistUserRealNames"
              >他人</Checkbox
            >

            <SelectUserInput
              :hadUsers="dataRef['hadUsers']"
              v-model:value="dataRef.distUserRealNames"
              @change="(val, node) => handleUserRealNames(val, node)"
              :isSelect="isMultiDeptistUserRealNames"
              v-if="dataRef.others"
            />
          </Space>
        </FormItemRest>
      </template>

      <template #file>
        <Upload
          name="file"
          :beforeUpload="() => false"
          :showUploadList="false"
          :multiple="true"
          @change="handleChangeFile"
        >
          <Button>
            <upload-outlined />
            上传文件
          </Button>
        </Upload>
      </template>
    </BasicForm>
    <BasicTable @register="registerTableFile" @resize-column="handleResizeColumn">
      <template #name="{ text, record }">
        <a
          @click="handleView(record)"
          v-if="
            text &&
            text.split('.')[1] &&
            (fileTyle.indexOf(text.split('.')[1]) != -1 || record.previewUrl)
          "
          >{{ text }}</a
        >
        <span v-else>{{ text }}</span>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'ion:download-outline',
              tooltip: '下载',
              onClick: handleDownload.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                placement: 'leftBottom',
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
              ifShow: () => type != 'info',
            },
          ]"
        />
      </template>
    </BasicTable>
    <!-- <div class="text-left" v-if="type != 'info'"
      >注: 日程修改时，如果是分配给他人的，不联动修改</div
    > -->
    <Modal v-model:visible="visible" width="100%" wrap-class-name="full-modal">
      <img :src="imgUrl" alt="" />
      <template #footer>
        <a-button @click="visible = false">取消</a-button>
      </template>
    </Modal>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Select, Form, Checkbox, Space, Upload, Button, Modal } from 'ant-design-vue';
  import {
    formSchema,
    timeRemind,
    columnsFile,
    formSchemaInfo,
    fileTyle,
  } from './allSchedule.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { UploadOutlined } from '@ant-design/icons-vue';

  import {
    getPlanCreate,
    getPlanUpdate,
    getPlan,
    getPlanAttachmentUpload,
    getPlanAttachmentListByPlanId,
    getPlanAttachmentDel,
    getPlanAttachmentDownload,
  } from '/@/api/workOffice/workOffice';
  import { isArray } from '/@/utils/is';
  import { dateUtil as dayjs } from '/@/utils/dateUtil';
  import { SelectUserInput } from '/@/components/CustomComp';
  import { downloadByData } from '/@/utils/file/download';
  import { bufToUrl } from '/@/utils/file/base64Conver';
  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    name: 'AllScheduleDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      Select,
      FormItemRest: Form.ItemRest,
      Checkbox,
      Space,
      SelectUserInput,
      BasicTable,
      TableAction,
      Upload,
      UploadOutlined,
      Button,
      Modal,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage, createConfirm } = useMessage();
      const isUpdate = ref(true);
      const type = ref('');
      let dataRef = ref<Recordable>({});
      const isMultiDeptistUserRealNames = ref(false);
      const userStore = useUserStore();

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema, resetSchema }] =
        useForm({
          labelWidth: 90,
          schemas: formSchema,
          showActionButtonGroup: false,
        });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false, showOkBtn: data?.type == 'info' ? false : true });
        isUpdate.value = !!data?.isUpdate;
        dataRef.value = {};

        type.value = data?.type;

        if (data?.type == 'info') {
          resetSchema(formSchemaInfo);
        } else {
          resetSchema(formSchema);
        }
        if (unref(isUpdate)) {
          updateSchema([
            {
              field: 'closed',
              ifShow: true,
            },
          ]);
          getPlan({ id: data.record.id }).then((res) => {
            dataRef.value = res;
            dataRef.value.dates = [dataRef.value.myDate, dataRef.value.endDate];

            dataRef.value.mine = dataRef.value.mine == 1 ? true : false;
            dataRef.value.others = dataRef.value.others ? true : false;
            dataRef.value.hadUsers = [];
            if (dataRef.value.distUsers) {
              isMultiDeptistUserRealNames.value = false;
              const realNames = dataRef.value['distUserRealNames'].split(',');
              const userNames = dataRef.value.distUsers.split(',');
              realNames.forEach((item, index) => {
                dataRef.value['hadUsers'].push({
                  key: userNames[index],
                  name: userNames[index],
                  title: item,
                  realName: item,
                });
              });
            } else {
              isMultiDeptistUserRealNames.value = true;
            }
            handelSearchFile();
            setFieldsValue({
              ...dataRef.value,
            });
          });
        } else {
          updateSchema([
            {
              field: 'distributer',
              ifShow: false,
            },
          ]);
          dataRef.value = data?.record;
          dataRef.value = {
            mine: false,
            others: false,
            hadUsers: [],
            distUserRealNames: '',
            ...dataRef.value,
          };
          dataRef.value['before'] = 10;
          if (dataRef.value.myDate && dataRef.value.endDate) {
            dataRef.value.dates = [dataRef.value.myDate, dataRef.value.endDate];
          }
          if (data.dateVal) {
            dataRef.value['myDate'] = data.dateVal;
            dataRef.value['endDate'] = data.dateVal;
            dataRef.value.dates = [dataRef.value.myDate, dataRef.value.endDate];
          }
          dataRef.value.mine = true;
          dataRef.value.others = false;
          isMultiDeptistUserRealNames.value = true;
          setFieldsValue({
            ...dataRef.value,
          });
        }
      });

      const getTitle = computed(() =>
        !unref(isUpdate) ? '新增' : type.value == 'info' ? '详情' : '编辑',
      );

      const ishadSelect = computed(() => dataRef.value.mine || dataRef.value.others);

      async function handleSubmit() {
        try {
          const values = await validate();
          if (!ishadSelect.value) {
            createMessage.warning('将日程分配给不能为空');
            return;
          }
          let formDate = Object.assign({}, dataRef.value, values);
          formDate.shared = formDate.shared ? '1' : '0';
          formDate.isClosed = formDate.closed ? '1' : '0';
          formDate.mine = formDate.mine ? '1' : '0';
          formDate.others = formDate.others ? '1' : '0';
          if (formDate.others != '1') {
            formDate.distUsers = '';
            formDate.distUserRealNames = '';
          }
          if (isArray(formDate.dates) && formDate.dates.length) {
            formDate.myDate = dayjs(formDate.dates[0]).format('YYYY-MM-DD HH:mm:ss');
            formDate.endDate = dayjs(formDate.dates[1]).format('YYYY-MM-DD HH:mm:ss');
          }
          const fileList = getDataSource();
          if (fileList && fileList.length) {
            formDate.attachments = fileList.map((item) => item.id).join(',');
          }
          console.log('formDate', formDate);
          delete formDate.dates;
          delete formDate.hadUsers;
          setDrawerProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            await getPlanUpdate(formDate);
          } else {
            await getPlanCreate(formDate);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      const handleUserRealNames = (val, node) => {
        console.log('node', val, node);
        const { dataRef: _dataRef, selectUsers } = node;
        dataRef.value.distUsers = _dataRef.userNames;
        dataRef.value.distUserRealNames = val;
        dataRef.value.hadUsers = selectUsers;
      };

      //附件
      const [
        registerTableFile,
        { reload, setTableData, insertTableDataRecord, deleteTableDataRecord, getDataSource },
      ] = useTable({
        title: '',
        api: getPlanAttachmentListByPlanId,
        columns: columnsFile,
        formConfig: {
          labelWidth: 120,
          schemas: [],
        },
        searchInfo: {
          op: 'search',
        }, //额外的参数
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        immediate: false,
        canResize: false,
        beforeFetch: (info) => {
          info.planId = dataRef.value.id;
          return info;
        },
        rowKey: 'id',
        pagination: false,
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
      });

      const handelSearchFile = () => {
        if (dataRef.value.id) {
          reload();
        } else {
          setTableData([]);
        }
      };

      async function handleChangeFile(info: Recordable) {
        console.log('info', info);
        const file = info.file;
        await handleGetPlanAttachmentUpload(file);
      }
      //文件上传
      const handleGetPlanAttachmentUpload = async (file) => {
        try {
          setDrawerProps({ confirmLoading: true });
          const formData = new FormData();
          formData.append('file', file);
          const res = await getPlanAttachmentUpload(formData);
          setDrawerProps({ confirmLoading: false });
          console.log('handleGetPlanAttachmentUpload-res', res);
          insertTableDataRecord(res, 0);
        } catch (error) {
          console.error('handleGetPlanAttachmentUpload', error);
          setDrawerProps({ confirmLoading: false });
        }
      };
      //下载
      const handleDownload = async (record) => {
        console.log('record', record);
        try {
          setDrawerProps({ confirmLoading: true });
          const data = await getPlanAttachmentDownload({ id: record.id });
          if (data) {
            downloadByData(data, `${record.name}`);
          }
          setDrawerProps({ confirmLoading: false });
        } catch (error) {
          setDrawerProps({ confirmLoading: false });
        }
      };
      //删除
      const handleDelete = async (record) => {
        try {
          setDrawerProps({ confirmLoading: true });
          await getPlanAttachmentDel({ id: record.id });
          await deleteTableDataRecord(record.id);
          setDrawerProps({ confirmLoading: false });
        } catch (error) {
          setDrawerProps({ confirmLoading: false });
        }
      };

      let serverInfo = userStore.getServerInfo;
      const visible = ref(false);
      const imgUrl = ref('');
      const handleView = async (record) => {
        if (fileTyle.indexOf(record.name.split('.')[1]) != -1) {
          let id = record.id;
          console.log('record', id);
          try {
            const data = await getPlanAttachmentDownload({ id: id });
            if (data) {
              const url = bufToUrl(data);
              imgUrl.value = url;
              visible.value = true;
            }
          } catch (error) {}
          return;
        }
        if (record.previewUrl) {
          window.open(serverInfo.rootPath + '/' + record.previewUrl);
        }
      };

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        timeRemind,
        dataRef,
        handleUserRealNames,
        isUpdate,
        isMultiDeptistUserRealNames,
        type,
        registerTableFile,
        handleResizeColumn: (w, col) => {
          col.width = w;
        },
        handleDownload,
        handleDelete,
        handleChangeFile,
        handleView,
        fileTyle,
        visible,
        imgUrl,
      };
    },
  });
</script>

<style lang="less">
  .full-modal {
    .ant-modal {
      max-width: 100%;
      top: 0;
      padding-bottom: 0;
      margin: 0;
    }
    .ant-modal-content {
      display: flex;
      flex-direction: column;
      height: calc(100vh);
    }
    .ant-modal-body {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
</style>
